package chen.yi.component.code.generator.service.element;

import chen.yi.component.code.generator.entity.ElementInfoPO;
import chen.yi.component.code.generator.mapper.ElementInfoMapper;
import chen.yi.component.code.generator.vo.ElementInfoVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author huat
 **/
@Service
@Slf4j
public class ElementInfoServiceImpl extends ServiceImpl<ElementInfoMapper, ElementInfoPO> implements ElementInfoService{

    @Override
    public List<ElementInfoVO> getAllElementInfo(String terminal) {
        List<ElementInfoVO> allElementInfo = this.getBaseMapper().getAllElementInfo(terminal);
        log.info("获取到的元素数据:{}", allElementInfo);
        //将元素转为map，key为id
        Map<Integer, ElementInfoVO> elementTree = allElementInfo.stream()
                .collect(Collectors.toMap(ElementInfoVO::getId, node -> node));
        List<ElementInfoVO> roots = new ArrayList<>();
        allElementInfo.forEach(item->{
            if(item.getParentId().equals(0)){
                roots.add(item);
            }else{
                ElementInfoVO parent = elementTree.get(item.getParentId());
                if(Objects.nonNull(parent)){
                    if(parent.getChildren()==null){
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(item);
                }
            }
        });
        return roots;
    }

}
